﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace aaAttributeBrowser
{
    public partial class MainForm : Form
    {
        Nancy _nancy = new Nancy();
        private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public MainForm()
        {
            InitializeComponent();
            txtListenPort.Text = _nancy.ListenPort.ToString();
        }

        public MainForm(Options options)
        {
            InitializeComponent();
            _nancy.ListenPort = options.ListenPort;
            txtListenPort.Text = _nancy.ListenPort.ToString();
            chkHttps.Checked = options.Https;
            if (options.Autostart)
            {
                if (_nancy.StartListening(chkHttps.Checked))
                    btnStartServer.Text = "Stop Server";
            }
        }

        void attribMgr_Message(string message)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => attribMgr_Message(message)));
                return;
            }
            txtLog.AppendText(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ":" +  message + Environment.NewLine);
        }

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            if (btnStartServer.Text == "Start Server")
            {
                if (_nancy.StartListening(chkHttps.Checked))
                btnStartServer.Text = "Stop Server";
            }
            else
            {
                _nancy.StopListening();
                btnStartServer.Text = "Start Server";
            }
        }

        private void txtListenPort_TextChanged(object sender, EventArgs e)
        {
            try
            {
                _nancy.ListenPort = int.Parse(txtListenPort.Text);
            }
            catch { }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            _nancy.StopListening();
        }
        
    }
}
